package com.amt.util;
import com.amt.configure.ResultMsg;
import com.amt.configure.Upload;
import lombok.extern.slf4j.Slf4j;
import org.iherus.codegen.qrcode.QrcodeConfig;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @Title: QrCodeUtil.java 
 * @Package com.amt.util 
 * @Description: TODO(二维码工具类) 
 * @author 江伟  
 * @date 2021年03月5日 下午2:47:45
 * Copyright (c) ©1994-2021 Scjydz.com All Rights Reserved.
 */
@Slf4j
@Component
public class QrCodeUtil {
	@Autowired
	private Upload upload;
	
	/**
	 * @description: 创建二维码图片
	 * @param content 二维码内容
	 * @param width 宽度
	 * @param height 高度
	 * @return 加密的二维码图片路径
	 */
	public ResultMsg createQrCodeImage(String content,int width,int height) {
		QrcodeConfig config = new QrcodeConfig().setWidth(width).setHeight(height);
		StringBuilder sb = new StringBuilder();
		sb.append(upload.getBaseCardPath("extractionCode/")).append(UUID.randomUUID().toString().replaceAll("-", "").toUpperCase()).append(".png");
		try { 
			boolean result = new SimpleQrcodeGenerator(config).generate(content).toFile(sb.toString());
			if (result) {
				config = null;
				return new ResultMsg(200, "创建二维码成功", null, Base64Util.encodeData(sb.toString().replace(upload.getBasePath(), "")));
			}
		} catch (IOException e) {
			log.error("生成二维码错误：{}", e);
		}
		return new ResultMsg(201,"创建二维码失败");
	}
	
	/**
	 * @description: 创建电子健康卡二维码图片，附带居民健康卡LOGO
	 * @param content 二维码内容
	 * @return 加密的二维码图片路径
	 */
	public ResultMsg createHealthCardQrCodeImage(String content) {
		// 文件存放路径
		StringBuilder sb = new StringBuilder();
		sb.append(upload.getBaseCardPath("card/")).append(UUID.randomUUID().toString().replaceAll("-", "").toUpperCase()).append(".png");
		QrcodeConfig config = new QrcodeConfig().setWidth(300).setHeight(300);
		try {
		    boolean result = new SimpleQrcodeGenerator(config).setLogo(upload.getBaseCardPath("card/") + "healthcard.png")
					.generate(content).toFile(sb.toString());
			if (result) {
				config = null;
				return new ResultMsg(200, "创建电子健康卡二维码成功", null, Base64Util.encodeData(sb.toString().replace(upload.getBasePath(), "")));
			}
		} catch (FileNotFoundException e) {
			log.error("电子健康卡二维码 FileNotFoundException{}", e);
		} catch (IOException e) {
			log.error("电子健康卡二维码IOException{}", e);
		}  
		 
		return new ResultMsg(201,"创建电子健康卡二维码失败");
	}
	
	

	

}
